<?php


namespace app\index\controller;

use think\console\Output;
use think\Exception;
use think\Image;
class Upfile extends Site
{
    /**++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
     * ➡ 视频上传音频
     **+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++**/
    /**
     * 上传视频音频
     * @throws Exception
     * @throws \think\exception\PDOException
     */
    public function upvideo(){
        $code="1";$data=[];
        if(isset($_FILES["myfile"])){
            $file = $this->request->file();
            $code="2";
            if(isset($file['myfile']) && $file['myfile']){
                $file =$file['myfile'];
                $hash=$file->hash();//唯一值
                //判断库中文件是否重复
                $this->set_cache("hash_file",$hash);
                $hash_arr = $this->get_cache("hash_file");
                $is_hash = $this->array_is_str_one($hash_arr,$hash);
                if($is_hash){
                    //查询信息并返回
                    $fileinfo = $this->get_tab_info(" where hash='".$hash."'");
                    if(isset($fileinfo[0]) && $fileinfo[0]){
                        $fileinfo = $fileinfo[0];
                        $data=['uuid'=>$fileinfo['uuid'],'mp4_url'=>$fileinfo['file_path'].$fileinfo['file_name'],'jpg_url'=>$fileinfo['file_path'].$fileinfo['file_name_sn']."","size"=>$fileinfo['size'],'hash'=>$hash];
                        echo json_encode(['code'=>0,'msg'=>"ok",'data'=>$data]);$fileinfo=null;$data=null;$hash_arr=null;$is_hash=null;$hash=null;
                        die;
                    }
                    $fileinfo=null;
                }
                $file_path=ROOT_PATH . 'public' . DS . 'uploads'.DS."video".DS.date("Ym");
                //判断文件夹是否存在
                if(!is_dir($file_path)){
                    mkdir($file_path, 0777);
                }
                //判断文件是否为视频文件
                $file_type= $_FILES['myfile']['type'];
                $file_type_arr=['video/mp4','audio/mp3'];//允许的上传视频格式
                $code="3";
                if(in_array($file_type,$file_type_arr)){
                    //获取文件后缀
                    $ext_file =explode('.',$_FILES['myfile']['name'])[1];
                    $name_file=date("YmdHis").rand(10000,99999);
                    $file_path = $file_path.DS.$name_file.'.'.$ext_file;
                    $video_img_path=ROOT_PATH . 'public' . DS . 'uploads'.DS."video".DS.date("Ym").DS;
                    move_uploaded_file($_FILES["myfile"]["tmp_name"],$file_path);
                    //截取名称
                    //截取第二帧当封面图
                    $jpg = $name_file.".jpg";$img_status=false;
                    if(!strstr($file_type,"mp3")){
                        $img_status= $this->getVideoCover($file_path,"2",$video_img_path.$jpg);
                    }
                    $domain=get_current_url_ym()."/uploads/video/".date("Ym")."/";
                    $uuid = $this->uuid();
                    $data=['uuid'=>$uuid,'mp4_url'=>$domain.$name_file.'.'.$ext_file,'jpg_url'=>$img_status?($domain.$jpg):"","size"=>$_FILES['myfile']['size'],'hash'=>$hash];
                    //加入数据表
                    $this->add_tab_info([
                        'uuid'=>$uuid,
                        'hash'=>$hash,
                        'file_name'=>$name_file.'.'.$ext_file,
                        'file_path'=>"/uploads/video/".date("Ym")."/",
                        'file_name_sn'=>$jpg,
                        'size'=>$data['size'],
                        'type'=>$file_type
                    ]);
                    $code=0;
                    $ext_file=null;$name_file=null;$video_img_path=null;$jpg=null;$img_status=null;$domain=null;
                }
                $file_type_arr=null;$file_type=null;$file_path=null;$hash=null;
            }
            $file=null;
        }
        $error=["ok","文件错误，上传失败","file名称错误，上传失败","文件后缀名错误，上传文件失败"];
        echo json_encode(['code'=>$code,'msg'=>$error[intval($code)],'data'=>$data]);
        $error=null;$data=null;$code=null;
    }
    /**
     * 截取视频
     * @param $file
     * @param $time
     * @param $name
     * @return bool
     */
    private function getVideoCover($file,$time,$name) {
        //1.PHP允许使用system服务
        //2.系统必须安装ffmpeg
        $str = "/usr/bin/ffmpeg -i ".$file." -y -f mjpeg -ss 2 -t ".$time." -s 320x240 ".$name;
        //var_dump($fkg);//执行状态：0：正常；127：命令不存在
        try{
            system($str,$fkg);
        }catch (Exception $e){
            $fkg=127;
        }
        if($fkg===127){
            $str=null;
            return false;
        }
        $str=null;
        return true;
    }


    /**++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
     * ➡ 图片上传
     **+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++**/
    /**
     * 图片上传并生成压缩文件
     * @return array|\think\response\Json
     * @throws Exception
     * @throws \think\exception\PDOException
     */
    public function upimg(){
        $file = $this->request->file('file');
        $fileurl = date("Ym");
        $error="";$data=[];
        if(!empty($file)){
            // 移动到框架应用根目录/public/uploads/ 目录下
            $key_haxi =$file->hash();
            //判断库中文件是否重复
            $this->set_cache("hash_file",$key_haxi);
            $hash_arr = $this->get_cache("hash_file");
            $is_hash = $this->array_is_str_one($hash_arr,$key_haxi);
            if($is_hash){
                //查询信息并返回
                $fileinfo = $this->get_tab_info(" where hash='".$key_haxi."'");
                if(isset($fileinfo[0]) && $fileinfo[0]){
                    $fileinfo = $fileinfo[0];
                    $data=['uuid'=>$fileinfo['uuid'],'jpg_url'=>get_current_url_ym().$fileinfo['file_path'].$fileinfo['file_name'],'jpg_url_sn'=>get_current_url_ym().$fileinfo['file_path'].$fileinfo['file_name_sn']."","size"=>$fileinfo['size'],'hash'=>$key_haxi];
                    $data['src']=$data['jpg_url'];
                    $fileinfo=null;$hash_arr=null;$is_hash=null;$hash=null;
                    return json(['code'=>0,'msg'=>"ok",'data'=>$data]);
                }
                $fileinfo=null;
            }
            $max_size=5242880*2;//10M
            if($file->getMime()=='video/mp4'){
                $max_size = $max_size*2;
            }
            //限制最大5M
            $info = $file->validate(['size'=>$max_size,'ext'=>'jpg,png,gif,mp4,mp3,jpeg'])->rule('uniqid')->move(ROOT_PATH . 'public' . DS . 'uploads'.DS."img".DS.$fileurl);
            $error = $file->getError();
            //验证文件后缀后大小
            if(!empty($error)){
                return json(['code'=>0,'msg'=>$error,'status'=>false]);
            }
            if($info){
                // 成功上传后 获取上传信息
                // 输出 jpg
                //$info->getExtension();
                // 输出 20160820/42a79759f284b767dfcb2a0197904287.jpg
                //$info->getSaveName();
                // 输出 42a79759f284b767dfcb2a0197904287.jpg
                //缩略图
                $full_name=$full_name_dt = $info->getFilename();
                $size_img = $info->getSize()/1024/1024;
                $img_size_dt=$info->getSize();
                $ext = explode('.',$full_name_dt);
                if(isset($ext[1]) && $ext[1]){
                    $ext = $ext[1];
                }
                $ext=strtolower($ext);
                //var_dump($ext);var_dump($full_name);var_dump($size_img);die;
                if($size_img > 1 && !is_array($ext) && in_array($ext,['jpg','png','gif','jpeg'])){
                    vendor("topthink.think-image.src.Image",'.php');
                    $imgaes= Image::open($info);
                    $width = $imgaes->width();
                    $height = $imgaes->height();
                    $full_name = "_slt_".$full_name_dt;
                    if($size_img > 5){
                        $width = $width/10;
                        $height = $height/10;
                    }else{
                        $width = $width/2;
                        $height = $height/2;
                    }
                    $imgaes->thumb($width,$height)->save(ROOT_PATH . 'public' . DS . 'uploads'.DS."img".DS.$fileurl.DS.$full_name);
                    $imgaes=null;$width=null;$height=null;
                }
                $photo = get_current_url_ym().'/uploads/img/'.$fileurl;
                //存入数据库
                $uuid = $this->uuid();
                $this->add_tab_info([
                    'uuid'=>$uuid,
                    'hash'=>$key_haxi,
                    'file_name'=>$full_name_dt,
                    'file_path'=>"/uploads/img/".date("Ym")."/",
                    'file_name_sn'=>$full_name,
                    'size'=>$img_size_dt,
                    'type'=>$info->getType()
                ]);
                $data=[
                    'uuid'=>$uuid,
                    'jpg_url'=>$photo.'/'.$full_name_dt,
                    'src'=>$photo.'/'.$full_name_dt,
                    'jpg_url_sn'=>$photo.'/'.$full_name,
                    "size"=>$img_size_dt,'hash'=>$key_haxi
                ];
                $photo = null;$full_name=null;$full_name_dt=null;
            }else{
                // 上传失败获取错误信息
                $file->getError();
            }
        }
        $file=null;$key_haxi=null;$fileurl=null;
        if($data){
            return json(['msg'=>"ok",'code'=>0,'data'=>$data]);
        }else{
            return json(['msg'=>$error,'code'=>1,'data'=>$data]);
        }
    }

    /**++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
     * ➡ 文件上传
     **+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++**/
    /**
     * 文件上传
     * @throws Exception
     * @throws \think\exception\PDOException
     */
    public function upfile(){
        $code="1";$data=[];
        if(isset($_FILES["myfile"])){
            $file = $this->request->file();
            $code="2";
            if(isset($file['myfile']) && $file['myfile']){
                $file =$file['myfile'];
                $hash=$file->hash();//唯一值
                //判断库中文件是否重复
                $this->set_cache("hash_file",$hash);
                $hash_arr = $this->get_cache("hash_file");
                $is_hash = $this->array_is_str_one($hash_arr,$hash);
                if($is_hash){
                    //查询信息并返回
                    $fileinfo = $this->get_tab_info(" where hash='".$hash."'");
                    if(isset($fileinfo[0]) && $fileinfo[0]){
                        $fileinfo = $fileinfo[0];
                        $data=['uuid'=>$fileinfo['uuid'],'url'=>$fileinfo['file_path'].$fileinfo['file_name'],"size"=>$fileinfo['size'],'hash'=>$hash];
                        echo json_encode(['code'=>0,'msg'=>"ok",'data'=>$data]);$fileinfo=null;$data=null;$hash_arr=null;$is_hash=null;$hash=null;
                        die;
                    }
                    $fileinfo=null;
                }
                $file_path=ROOT_PATH . 'public' . DS . 'uploads'.DS."file".DS.date("Ym");
                //判断文件夹是否存在
                if(!is_dir($file_path)){
                    mkdir($file_path, 0777);
                }
                //判断文件是否为视频文件
                $file_type= $_FILES['myfile']['type'];
                $file_type_arr=['application/x-zip-compressed','application/pdf','application/x-gzip','application/octet-stream'];//允许的上传视频格式 zip  pdf  7z rar  gz
                $code="3";
                if(in_array($file_type,$file_type_arr)){
                    //获取文件后缀
                    $ext_file =explode('.',$_FILES['myfile']['name'])[1];
                    $name_file=date("YmdHis").rand(10000,99999);
                    $file_path = $file_path.DS.$name_file.'.'.$ext_file;
                    move_uploaded_file($_FILES["myfile"]["tmp_name"],$file_path);
                    //截取名称
                    $domain=get_current_url_ym()."/uploads/file/".date("Ym")."/";
                    $uuid = $this->uuid();
                    $data=['uuid'=>$uuid,'url'=>$domain.$name_file.'.'.$ext_file,"size"=>$_FILES['myfile']['size'],'hash'=>$hash];
                    //加入数据表
                    $this->add_tab_info([
                        'uuid'=>$uuid,
                        'hash'=>$hash,
                        'file_name'=>$name_file.'.'.$ext_file,
                        'file_path'=>"/uploads/file/".date("Ym")."/",
                        'file_name_sn'=>"",
                        'size'=>$data['size'],
                        'type'=>$file_type
                    ]);
                    $code=0;
                    $ext_file=null;$name_file=null;$video_img_path=null;$jpg=null;$img_status=null;$domain=null;
                }
                $file_type_arr=null;$file_type=null;$file_path=null;$hash=null;
            }
            $file=null;
        }
        $error=["ok","文件错误，上传失败","file名称错误，上传失败","文件后缀名错误，上传文件失败"];
        echo json_encode(['code'=>$code,'msg'=>$error[intval($code)],'data'=>$data]);
        $error=null;$data=null;$code=null;
    }
}